// go run this file
// test passed on Windows
package main

import (
	"encoding/json"
	"io"
	"net/http"
	"net/url" // 导入 url 包用于编码

	"github.com/fatih/color"
)

// JokeResponse 定义从 icanhazdadjoke.com 返回的笑话数据结构
type JokeResponse struct {
	ID     string `json:"id"`
	Joke   string `json:"joke"`
	Status int    `json:"status"`
}

// TranslationResponse 定义从翻译 API 返回的数据结构
type TranslationResponse struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		Source string `json:"source"`
		Target string `json:"target"`
	} `json:"data"`
}

func main() {
	var colorPrinter = color.New(color.FgCyan).Add(color.Underline)

	// 第一步：从 icanhazdadjoke.com 获取一个随机笑话
	jokeURL := "https://icanhazdadjoke.com/"
	req, err := http.NewRequest("GET", jokeURL, nil)
	if err != nil {
		colorPrinter.Println("Error creating joke request:", err)
		return
	}

	// 设置请求头，指定接受 JSON 格式
	req.Header.Set("Accept", "application/json")
	req.Header.Set("User-Agent", "Go-http-client/1.1")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		colorPrinter.Println("Error fetching joke:", err)
		return
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		colorPrinter.Println("Error reading joke response body:", err)
		return
	}

	// 解析 JSON 响应
	var joke JokeResponse
	err = json.Unmarshal(body, &joke)
	if err != nil {
		colorPrinter.Println("Error unmarshaling joke data:", err)
		return
	}

	colorPrinter.Println("随机笑话：", joke.Joke)

	// 第二步：将笑话内容传递给翻译 API
	// 对 joke.Joke 进行 URL 编码
	encodedJoke := url.QueryEscape(joke.Joke) // 使用 url.QueryEscape 对字符串进行编码
	translationURL := "https://api.52vmy.cn/api/query/fanyi?msg=" + encodedJoke

	// 创建翻译请求
	translationReq, err := http.NewRequest("GET", translationURL, nil)
	if err != nil {
		colorPrinter.Println("Error creating translation request:", err)
		return
	}

	// 设置请求头
	translationReq.Header.Set("Accept", "application/json")
	translationReq.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")

	// 发送翻译请求
	translationResp, err := client.Do(translationReq)
	if err != nil {
		colorPrinter.Println("Error fetching translation:", err)
		return
	}
	defer translationResp.Body.Close()

	// 读取翻译响应体
	translationBody, err := io.ReadAll(translationResp.Body)
	if err != nil {
		colorPrinter.Println("Error reading translation response body:", err)
		return
	}

	// 解析翻译响应
	var translation TranslationResponse
	err = json.Unmarshal(translationBody, &translation)
	if err != nil {
		colorPrinter.Println("Error unmarshaling translation data:", err)
		return
	}

	// 检查翻译结果
	if translation.Code == 200 {
		colorPrinter.Println("翻译结果：", translation.Data.Target)
	} else {
		colorPrinter.Println("翻译失败，错误信息：", translation.Msg)
	}
}
